package de.nak.fireDepartment.administrationAction;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.LookupDispatchActionSupport;

import de.nak.fireDepartment.actionForms.DepartmentForm;
import de.nak.fireDepartment.exceptions.ErrorOnDeleteException;
import de.nak.fireDepartment.model.Car;
import de.nak.fireDepartment.model.Department;
import de.nak.fireDepartment.service.CarService;
import de.nak.fireDepartment.service.DepartmentService;
import de.nak.fireDepartment.service.ImageUploadService;
import de.nak.fireDepartment.service.LoginService;

/**
 * Action that works with a department
 * 
 * @author Sven Redelin
 */
public class DepartmentAction extends LookupDispatchActionSupport {
	
	/**
	 * This method shows the selected departdment into the departmentForm
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward showDepartment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => DepartmentForm
		DepartmentForm departmentForm = (DepartmentForm) form;
		DepartmentService departmentService = (DepartmentService) getWebApplicationContext().getBean("departmentService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(departmentForm.getSelectedKey()==null){
			departmentForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get the department
		Department department = departmentService.showDepartment(departmentForm.getSelectedKey());
		
		// if department has no image set default image
		if (department.getImageURL() == null || department.getImageURL().equals("")){
			department.setImageURL("/FireDepartmentManagement/images/layout/noImage.jpg");
		}
		
		// store department and data in form
		departmentForm.setDepartment(department);
		departmentForm.setErrorCode("");
		// Return result
		return mapping.findForward("show");
	}
	
	/**
	 * This method prepares to create a department
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward createDepartment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => DepartmentForm
		DepartmentForm departmentForm = (DepartmentForm) form;
		CarService carService = (CarService) getWebApplicationContext().getBean("carService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// list available cars
		Collection<Car> cars = carService.listCars();
		// create a new department
		Department department = new Department();
		// store values in departmentForm
		departmentForm.setDepartment(department);
		departmentForm.setCars(cars);
		departmentForm.setSelectedCarIds(new Long[cars.size()]);
		departmentForm.setSelectedCarNames(new LinkedList<String>());
		departmentForm.setErrorCode("");
		// Return result
		return mapping.findForward("create");
	}
	
	/**
	 * This method prepares to edit a department
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward editDepartment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => DepartmentForm
		DepartmentForm departmentForm = (DepartmentForm) form;
		DepartmentService departmentService = (DepartmentService)getWebApplicationContext().getBean("departmentService");
		CarService carService = (CarService) getWebApplicationContext().getBean("carService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(departmentForm.getSelectedKey()==null){
			departmentForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get available cars
		Collection<Car> cars = carService.listCars();
		// get selected department
		Department department = departmentService.showDepartment(departmentForm.getSelectedKey());
		// get cars of selected department
		Collection<Car> carsOfDept = department.getCars();
		
		//Iterate over all Cars to get the Cars of the Department for the selectionlist
		int i = 0;
		Long[] selectedCarIds = new Long[cars.size()];
		Collection <String> selectedCarNames = new LinkedList<String>();
		for (Car car : cars) {
			for (Car carOfDept : carsOfDept) {
				if(car.equals(carOfDept)){
					selectedCarIds[i] = car.getCarId();
					selectedCarNames.add(car.getModelName());
					i++;
				}
			}
		}
		
		// store values in departmentForm
		departmentForm.setSelectedCarIds(selectedCarIds);
		departmentForm.setSelectedCarNames(selectedCarNames);
		departmentForm.setDepartment(department);
		departmentForm.setCars(cars);
		departmentForm.setErrorCode("");
		// Return result
		return mapping.findForward("edit");
	}
	
	/**
	 * This method deletes the selected department
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward deleteDepartment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => DepartmentForm
		DepartmentForm departmentForm = (DepartmentForm) form;
		DepartmentService departmentService = (DepartmentService)getWebApplicationContext().getBean("departmentService");
		ImageUploadService imageUploadService = (ImageUploadService)getWebApplicationContext().getBean("imageUploadService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(departmentForm.getSelectedKey()==null){
			departmentForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get the selected department
		Department dept = departmentService.showDepartment(departmentForm.getSelectedKey());
		String imageURL = dept.getImageURL();
		try{
			// delete the department
			departmentService.deleteDepartment(departmentForm.getSelectedKey());
			// delete the linked image of the departdment
			imageUploadService.deleteImage(imageURL, getServletContext());
			// get the available list of departments an store values in form
			departmentForm.setDepartments(departmentService.listDepartments());
			departmentForm.setErrorCode("");
		}catch(ErrorOnDeleteException ex){
			departmentForm.setErrorCode(ex.getMessage());
		}
		// Return result
		return mapping.findForward("success");
	}

	
	/** {@inheritDoc} */
	@Override
	protected Map<String, String> getKeyMethodMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("button.show", "showDepartment");
		map.put("button.create", "createDepartment");
		map.put("button.edit", "editDepartment");
		map.put("button.delete", "deleteDepartment");
		return map;
	}
}
